package cn.tedu.weibo.controller;

import cn.tedu.weibo.mapper.UserMapper;
import cn.tedu.weibo.pojo.dto.UserLoginDto;
import cn.tedu.weibo.pojo.dto.UserRegDto;
import cn.tedu.weibo.pojo.entity.User;
import cn.tedu.weibo.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired(required = false)
    UserMapper mapper;

    @RequestMapping("/reg")
    public int reg(@RequestBody UserRegDto user){
        UserVO u = mapper.selectByUsername(user.getUsername());
        if (u!=null){
            return 2;//用户名已存在
        }
        User userEntity = new User();
        //把dto里面的数据装进实体类
        BeanUtils.copyProperties(user,userEntity);
        //把实体里面的数据保存到数据库里面
        mapper.insert(userEntity);
        return 1;//注册成功
    }

    @RequestMapping("/login")
    public int login(@RequestBody UserLoginDto user, HttpSession session){
        UserVO u = mapper.selectByUsername(user.getUsername());
        if (u!=null){
            if (u.getPassword().equals(user.getPassword())){
                //把当前登录的用户对象保存到 当前客户端对应的会话对象里面
                session.setAttribute("user",u);

                return 1;//登录成功
            }
            return 2;//密码错误
        }
        return 3;//用户名不存在
    }
    @RequestMapping("/currentUser")
    public UserVO currentUser(HttpSession session){
        //取出会话对象中的user 响应给客户端
        return (UserVO) session.getAttribute("user");
    }

    @RequestMapping("/logout")
    public void logout(HttpSession session){
        //删除登录成功时保存的用户对象
        session.removeAttribute("user");
    }

}



